package com.example.teachingevaluationsystem.config.auth;

import cn.hutool.json.JSONUtil;
import com.example.teachingevaluationsystem.common.ResultCode;
import com.example.teachingevaluationsystem.config.rest.BaseResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/** 没有访问权限返回
 * @author liupeng*/
@Component
public class RestfulAccessDeniedHandler implements AccessDeniedHandler {
  @Override
  public void handle(
      HttpServletRequest request, HttpServletResponse response, AccessDeniedException e)
      throws IOException {
    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/json");
    BaseResponse<Object> responseBody =
        BaseResponse.builder()
            .message("token expired")
            .code(ResultCode.UN_LOGIN)
            .success(false)
            .build();
    response.getWriter().println(JSONUtil.parse(responseBody));
    response.getWriter().flush();
  }
}
